package com.ioandfile;

import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.Scanner;

public class ObjectOutPutStreamTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入第一位学生的姓名");
        String name = scanner.next();
        System.out.println("请输入第一位学生的年龄");
        int age = scanner.nextInt();
        Student student1 = new Student(name,age);
        System.out.println("请输入第二位学生的姓名");
        String name1 = scanner.next();
        System.out.println("请输入第二位学生的年龄");
        int age1 = scanner.nextInt();
        Student student2 = new Student(name1,age1);
        System.out.println("请输入第三位学生的姓名");
        String name2 = scanner.next();
        System.out.println("请输入第三位学生的年龄");
        int age2 = scanner.nextInt();
        Student student3 = new Student(name2,age2);

        OutputStream os = null;
        ObjectOutputStream oos= null;

        try {
            os = new FileOutputStream("/Users/edy/Desktop/file/student.txt");
            oos = new ObjectOutputStream(os);

            Student[] arr = {student1,student2,student2,null};
            for (Student student : arr) {
                oos.writeObject(student);
                oos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(oos);
            IOUtils.closeQuietly(os);
        }

        InputStream is = null;
        ObjectInputStream ois = null;

        try {
            is = new FileInputStream("/Users/edy/Desktop/file/student.txt");
            ois = new ObjectInputStream(is);

            Object obj ;
            while ((obj = ois.readObject()) != null ) {
                System.out.println(obj);
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}
